
var receiversId = [];





function findByItem(pageNO) {
    $("dialog").style.visibility = "visible";

    axios.get("/employee/findByItem", {
        params: {
            pageNO,
            name: $("nameInput").value,
            dept: $("deptInput").value
        }
    }).then(resp => {
        var info = resp.data;
        var str = "";
        info.records.forEach(n => {
            str += `<tr><td><input type="checkbox" name="emId" value="${n.emId}"></td><td>${n.realName}</td><td>${n.dept}</td><td>${n.job}</td></tr>`;
        })
        $("emData").innerHTML = str;
        var pageStr = "";
        for (let i = 1; i <= info.pages; i++) {
            pageStr += `<a style="margin-left: 10px" href="javascript:findByItem(${i})">${i}</a>`;
        }
        $("cutDiv").innerHTML = pageStr;
    })
}

/**
 * 添加员到发件人集合
 */
 function addReceiver() {
    var checkBoxArr = document.getElementsByName("emId");
    checkBoxArr.forEach(n => {
        if (n.checked) {
            receiversId.push(n.value);
        }
    });

    var paramObj = new URLSearchParams();
    paramObj.append("emIdArray", receiversId);
    axios.post("/employee/addReceiverToEmail", paramObj).then(resp => {
       if (resp.data=="ok"){
           //关闭弹窗
           $("dialog").style.visibility = "hidden";
           showReceiver();
       }
    });

}

/**
 * 显示发件人
 */
 async function showReceiver() {
    await axios.get("/employee/findByIdArray").then(resp=>{
       var receivers=resp.data;
       if (receivers!=""){
           receiversId=receivers.map(n=>n.emId);
           var str = "";
           receivers.forEach(e => {
               str += `<tr><td>${e.realName}</td><td>${e.dept}</td>
            <td><input type="button" value="删除" onclick="removeEm(${e.emId})"></td></tr>`
           })
           $("receiverData").innerHTML = str;
       }else {
           $("receiverData").innerHTML = "";
       }

    })

}


/**
 * 移除发件人
 */
function removeEm(id) {
    receiversId=receiversId.filter(n=>n!=id);

    console.log(receiversId);

    var paramObj = new URLSearchParams();
    paramObj.append("emIdArray", receiversId);
    axios.post("/employee/addReceiverToEmail", paramObj).then(resp => {
        if (resp.data=="ok"){
            showReceiver();
        }
    });
}

/**
 * 发送
 */
async function send() {
    let annexPath;
    let formData=new FormData;
    formData.append("annex",$("annex").files[0]);
    let config = {
        headers: {'Content-Type': 'multipart/form-data' }
    }
    await axios.post("/email/upload",formData,config).then(resp=>{
        annexPath=resp.data;
    });

    var paramObj = new URLSearchParams();
    paramObj.append("head", $("head").value);
    paramObj.append("content", $("content").value);
    paramObj.append("annex",annexPath);

    axios.post("/email/send", paramObj).then(resp => {
        if (resp.data=="ok"){
            alert("发送成功！")
            location.href="/write.html"
        }
    })

}